import * as echarts from 'echarts/core'
import { BarChart, LineChart } from 'echarts/charts'
import {
	TitleComponent,
	TooltipComponent,
	GridComponent,
	LegendComponent,
	MarkLineComponent,
	MarkAreaComponent
} from 'echarts/components'
import { UniversalTransition } from 'echarts/features'
import { CanvasRenderer } from 'echarts/renderers'

// 注册ECharts组件
echarts.use([
	TitleComponent,
	TooltipComponent,
	GridComponent,
	LegendComponent,
	MarkLineComponent,
	MarkAreaComponent,
	BarChart,
	LineChart,
	UniversalTransition,
	CanvasRenderer
])

// 数据判断工具函数
export const hasSubjectPractice = (subject: any) => {
	return (
		subject.practice && subject.practice.average_score && subject.practice.average_score.length > 0
	)
}

export const hasSubjectTheoryRates = (subject: any) => {
	return (
		subject.theory &&
		subject.theory.pass_rate &&
		subject.theory.excellent_rate &&
		subject.theory.pass_rate.length > 0 &&
		subject.theory.excellent_rate.length > 0
	)
}

export const hasSubjectPracticeRates = (subject: any) => {
	return (
		subject.practice &&
		subject.practice.pass_rate &&
		subject.practice.excellent_rate &&
		subject.practice.pass_rate.length > 0 &&
		subject.practice.excellent_rate.length > 0
	)
}

// 销毁图表实例
export const destroyCharts = (charts: Record<string, echarts.ECharts | null>) => {
	Object.keys(charts).forEach((key) => {
		if (charts[key]) {
			charts[key]?.dispose()
			charts[key] = null
		}
	})
}

// 渲染理论成绩预测图表
export const renderTheoryScoreChart = (
	chartElement: HTMLElement,
	subject: any,
	years: string[],
	charts: Record<string, echarts.ECharts | null>
) => {
	if (!chartElement) return

	const chartInstance = echarts.init(chartElement)
	charts.theoryScore = chartInstance

	// 准备历史数据
	const historyData = subject.history
		? subject.history.map((item: any) => ({
				year: item.year,
				value: item.theory_average_score
			}))
		: []

	// 准备预测数据
	const predictionData = subject.theory.average_score.map((item: any) => ({
		year: item.year,
		value: item.predicted_value,
		lowerCI: item.lower_ci,
		upperCI: item.upper_ci
	}))

	// 合并年份数据，确保唯一性和排序
	const allYears = [
		...new Set([
			...historyData.map((item: any) => item.year),
			...predictionData.map((item: any) => item.year)
		])
	].sort()

	const option = {
		title: {
			text: '理论成绩预测',
			left: 'center'
		},
		tooltip: {
			trigger: 'axis',
			formatter: function (params: any) {
				let result = `${params[0].axisValue}<br/>`
				params.forEach((param: any) => {
					if (param.seriesName === '历史数据') {
						result += `${param.seriesName}: ${param.data ? param.data.toFixed(2) : '-'}<br/>`
					} else if (param.seriesName === '预测值') {
						result += `${param.seriesName}: ${param.data ? param.data.toFixed(2) : '-'}<br/>`
					} else if (param.seriesName === '下限') {
						result += `${param.seriesName}: ${param.data ? param.data.toFixed(2) : '-'}<br/>`
					} else if (param.seriesName === '上限') {
						result += `${param.seriesName}: ${param.data ? param.data.toFixed(2) : '-'}<br/>`
					}
				})
				return result
			}
		},
		legend: {
			data: ['历史数据', '预测值', '下限', '上限'],
			bottom: 0
		},
		grid: {
			left: '3%',
			right: '4%',
			bottom: '10%',
			top: '15%',
			containLabel: true
		},
		xAxis: {
			type: 'category',
			data: allYears,
			name: '学年'
		},
		yAxis: {
			type: 'value',
			name: '分数',
			min: (value: any) => Math.floor(value.min - 5),
			max: (value: any) => Math.ceil(value.max + 5)
		},
		series: [
			{
				name: '历史数据',
				type: 'line',
				data: allYears.map((year) => {
					const item = historyData.find((h: any) => h.year === year)
					return item ? item.value : null
				}),
				symbol: 'circle',
				symbolSize: 8,
				lineStyle: {
					width: 3
				},
				itemStyle: {
					color: '#67C23A'
				}
			},
			{
				name: '预测值',
				type: 'line',
				data: allYears.map((year) => {
					const item = predictionData.find((p: any) => p.year === year)
					return item ? item.value : null
				}),
				symbol: 'circle',
				symbolSize: 8,
				lineStyle: {
					width: 3
				},
				itemStyle: {
					color: '#409EFF'
				}
			},
			{
				name: '下限',
				type: 'line',
				data: allYears.map((year) => {
					const item = predictionData.find((p: any) => p.year === year)
					return item ? item.lowerCI : null
				}),
				lineStyle: {
					width: 2,
					type: 'dashed'
				},
				itemStyle: {
					color: '#E6A23C'
				}
			},
			{
				name: '上限',
				type: 'line',
				data: allYears.map((year) => {
					const item = predictionData.find((p: any) => p.year === year)
					return item ? item.upperCI : null
				}),
				lineStyle: {
					width: 2,
					type: 'dashed'
				},
				itemStyle: {
					color: '#F56C6C'
				}
			}
		]
	}

	chartInstance.setOption(option)
}

// 渲染实践成绩预测图表
export const renderPracticeScoreChart = (
	chartElement: HTMLElement,
	subject: any,
	years: string[],
	charts: Record<string, echarts.ECharts | null>
) => {
	if (!chartElement) return

	const chartInstance = echarts.init(chartElement)
	charts.practiceScore = chartInstance

	// 准备历史数据
	const historyData = subject.history
		? subject.history.map((item: any) => ({
				year: item.year,
				value: item.practice_average_score
			}))
		: []

	// 准备预测数据
	const predictionData = subject.practice.average_score.map((item: any) => ({
		year: item.year,
		value: item.predicted_value,
		lowerCI: item.lower_ci,
		upperCI: item.upper_ci
	}))

	// 合并年份数据，确保唯一性和排序
	const allYears = [
		...new Set([
			...historyData.map((item: any) => item.year),
			...predictionData.map((item: any) => item.year)
		])
	].sort()

	const option = {
		title: {
			text: '实践成绩预测',
			left: 'center'
		},
		tooltip: {
			trigger: 'axis',
			formatter: function (params: any) {
				let result = `${params[0].axisValue}<br/>`
				params.forEach((param: any) => {
					if (param.seriesName === '历史数据') {
						result += `${param.seriesName}: ${param.data ? param.data.toFixed(2) : '-'}<br/>`
					} else if (param.seriesName === '预测值') {
						result += `${param.seriesName}: ${param.data ? param.data.toFixed(2) : '-'}<br/>`
					} else if (param.seriesName === '下限') {
						result += `${param.seriesName}: ${param.data ? param.data.toFixed(2) : '-'}<br/>`
					} else if (param.seriesName === '上限') {
						result += `${param.seriesName}: ${param.data ? param.data.toFixed(2) : '-'}<br/>`
					}
				})
				return result
			}
		},
		legend: {
			data: ['历史数据', '预测值', '下限', '上限'],
			bottom: 0
		},
		grid: {
			left: '3%',
			right: '4%',
			bottom: '10%',
			top: '15%',
			containLabel: true
		},
		xAxis: {
			type: 'category',
			data: allYears,
			name: '学年'
		},
		yAxis: {
			type: 'value',
			name: '分数',
			min: (value: any) => Math.floor(value.min - 5),
			max: (value: any) => Math.ceil(value.max + 5)
		},
		series: [
			{
				name: '历史数据',
				type: 'line',
				data: allYears.map((year) => {
					const item = historyData.find((h: any) => h.year === year)
					return item ? item.value : null
				}),
				symbol: 'circle',
				symbolSize: 8,
				lineStyle: {
					width: 3
				},
				itemStyle: {
					color: '#67C23A'
				}
			},
			{
				name: '预测值',
				type: 'line',
				data: allYears.map((year) => {
					const item = predictionData.find((p: any) => p.year === year)
					return item ? item.value : null
				}),
				symbol: 'circle',
				symbolSize: 8,
				lineStyle: {
					width: 3
				},
				itemStyle: {
					color: '#409EFF'
				}
			},
			{
				name: '下限',
				type: 'line',
				data: allYears.map((year) => {
					const item = predictionData.find((p: any) => p.year === year)
					return item ? item.lowerCI : null
				}),
				lineStyle: {
					width: 2,
					type: 'dashed'
				},
				itemStyle: {
					color: '#E6A23C'
				}
			},
			{
				name: '上限',
				type: 'line',
				data: allYears.map((year) => {
					const item = predictionData.find((p: any) => p.year === year)
					return item ? item.upperCI : null
				}),
				lineStyle: {
					width: 2,
					type: 'dashed'
				},
				itemStyle: {
					color: '#F56C6C'
				}
			}
		]
	}

	chartInstance.setOption(option)
}

// 渲染理论及格率/优秀率预测图表
export const renderTheoryRateChart = (
	chartElement: HTMLElement,
	subject: any,
	years: string[],
	charts: Record<string, echarts.ECharts | null>
) => {
	if (!chartElement) return

	const chartInstance = echarts.init(chartElement)
	charts.theoryRate = chartInstance

	// 准备历史数据
	const historyPassRateData = subject.history
		? subject.history.map((item: any) => ({
				year: item.year,
				value: item.theory_pass_rate
			}))
		: []

	const historyExcellentRateData = subject.history
		? subject.history.map((item: any) => ({
				year: item.year,
				value: item.theory_excellent_rate
			}))
		: []

	// 准备预测数据
	const predictionPassRateData = subject.theory.pass_rate.map((item: any) => ({
		year: item.year,
		value: item.predicted_value,
		lowerCI: item.lower_ci,
		upperCI: item.upper_ci
	}))

	const predictionExcellentRateData = subject.theory.excellent_rate.map((item: any) => ({
		year: item.year,
		value: item.predicted_value,
		lowerCI: item.lower_ci,
		upperCI: item.upper_ci
	}))

	// 合并年份数据，确保唯一性和排序
	const allYears = [
		...new Set([
			...historyPassRateData.map((item: any) => item.year),
			...predictionPassRateData.map((item: any) => item.year)
		])
	].sort()

	const option = {
		title: {
			text: '理论及格率/优秀率预测',
			left: 'center'
		},
		tooltip: {
			trigger: 'axis',
			formatter: function (params: any) {
				let result = `${params[0].axisValue}<br/>`
				params.forEach((param: any) => {
					if (param.data !== null) {
						const value = (param.data * 100).toFixed(2)
						result += `${param.seriesName}: ${value}%<br/>`
					}
				})
				return result
			}
		},
		legend: {
			data: [
				'历史及格率',
				'历史优秀率',
				'及格率-预测',
				'及格率-下限',
				'及格率-上限',
				'优秀率-预测',
				'优秀率-下限',
				'优秀率-上限'
			],
			bottom: 0
		},
		grid: {
			left: '3%',
			right: '4%',
			bottom: '10%',
			top: '15%',
			containLabel: true
		},
		xAxis: {
			type: 'category',
			data: allYears,
			name: '学年'
		},
		yAxis: {
			type: 'value',
			name: '比率',
			min: 0,
			max: 1,
			axisLabel: {
				formatter: '{value * 100}%'
			}
		},
		series: [
			{
				name: '历史及格率',
				type: 'line',
				data: allYears.map((year) => {
					const item = historyPassRateData.find((h: any) => h.year === year)
					return item ? item.value : null
				}),
				symbol: 'circle',
				symbolSize: 8,
				lineStyle: {
					width: 3
				},
				itemStyle: {
					color: '#909399'
				}
			},
			{
				name: '历史优秀率',
				type: 'line',
				data: allYears.map((year) => {
					const item = historyExcellentRateData.find((h: any) => h.year === year)
					return item ? item.value : null
				}),
				symbol: 'circle',
				symbolSize: 8,
				lineStyle: {
					width: 3
				},
				itemStyle: {
					color: '#67C23A'
				}
			},
			{
				name: '及格率-预测',
				type: 'line',
				data: allYears.map((year) => {
					const item = predictionPassRateData.find((p: any) => p.year === year)
					return item ? item.value : null
				}),
				symbol: 'circle',
				symbolSize: 8,
				lineStyle: {
					width: 3
				},
				itemStyle: {
					color: '#409EFF'
				}
			},
			{
				name: '及格率-下限',
				type: 'line',
				data: allYears.map((year) => {
					const item = predictionPassRateData.find((p: any) => p.year === year)
					return item ? item.lowerCI : null
				}),
				lineStyle: {
					width: 2,
					type: 'dashed'
				},
				itemStyle: {
					color: '#409EFF',
					opacity: 0.5
				}
			},
			{
				name: '及格率-上限',
				type: 'line',
				data: allYears.map((year) => {
					const item = predictionPassRateData.find((p: any) => p.year === year)
					return item ? item.upperCI : null
				}),
				lineStyle: {
					width: 2,
					type: 'dashed'
				},
				itemStyle: {
					color: '#409EFF',
					opacity: 0.5
				}
			},
			{
				name: '优秀率-预测',
				type: 'line',
				data: allYears.map((year) => {
					const item = predictionExcellentRateData.find((p: any) => p.year === year)
					return item ? item.value : null
				}),
				symbol: 'circle',
				symbolSize: 8,
				lineStyle: {
					width: 3
				},
				itemStyle: {
					color: '#E6A23C'
				}
			},
			{
				name: '优秀率-下限',
				type: 'line',
				data: allYears.map((year) => {
					const item = predictionExcellentRateData.find((p: any) => p.year === year)
					return item ? item.lowerCI : null
				}),
				lineStyle: {
					width: 2,
					type: 'dashed'
				},
				itemStyle: {
					color: '#E6A23C',
					opacity: 0.5
				}
			},
			{
				name: '优秀率-上限',
				type: 'line',
				data: allYears.map((year) => {
					const item = predictionExcellentRateData.find((p: any) => p.year === year)
					return item ? item.upperCI : null
				}),
				lineStyle: {
					width: 2,
					type: 'dashed'
				},
				itemStyle: {
					color: '#E6A23C',
					opacity: 0.5
				}
			}
		]
	}

	chartInstance.setOption(option)
}

// 渲染实践及格率/优秀率预测图表
export const renderPracticeRateChart = (
	chartElement: HTMLElement,
	subject: any,
	years: string[],
	charts: Record<string, echarts.ECharts | null>
) => {
	if (!chartElement) return

	const chartInstance = echarts.init(chartElement)
	charts.practiceRate = chartInstance

	// 准备历史数据
	const historyPassRateData = subject.history
		? subject.history.map((item: any) => ({
				year: item.year,
				value: item.practice_pass_rate
			}))
		: []

	const historyExcellentRateData = subject.history
		? subject.history.map((item: any) => ({
				year: item.year,
				value: item.practice_excellent_rate
			}))
		: []

	// 准备预测数据
	const predictionPassRateData = subject.practice.pass_rate.map((item: any) => ({
		year: item.year,
		value: item.predicted_value,
		lowerCI: item.lower_ci,
		upperCI: item.upper_ci
	}))

	const predictionExcellentRateData = subject.practice.excellent_rate.map((item: any) => ({
		year: item.year,
		value: item.predicted_value,
		lowerCI: item.lower_ci,
		upperCI: item.upper_ci
	}))

	// 合并年份数据，确保唯一性和排序
	const allYears = [
		...new Set([
			...historyPassRateData.map((item: any) => item.year),
			...predictionPassRateData.map((item: any) => item.year)
		])
	].sort()

	const option = {
		title: {
			text: '实践及格率/优秀率预测',
			left: 'center'
		},
		tooltip: {
			trigger: 'axis',
			formatter: function (params: any) {
				let result = `${params[0].axisValue}<br/>`
				params.forEach((param: any) => {
					if (param.data !== null) {
						const value = (param.data * 100).toFixed(2)
						result += `${param.seriesName}: ${value}%<br/>`
					}
				})
				return result
			}
		},
		legend: {
			data: [
				'历史及格率',
				'历史优秀率',
				'及格率-预测',
				'及格率-下限',
				'及格率-上限',
				'优秀率-预测',
				'优秀率-下限',
				'优秀率-上限'
			],
			bottom: 0
		},
		grid: {
			left: '3%',
			right: '4%',
			bottom: '10%',
			top: '15%',
			containLabel: true
		},
		xAxis: {
			type: 'category',
			data: allYears,
			name: '学年'
		},
		yAxis: {
			type: 'value',
			name: '比率',
			min: 0,
			max: 1,
			axisLabel: {
				formatter: '{value * 100}%'
			}
		},
		series: [
			{
				name: '历史及格率',
				type: 'line',
				data: allYears.map((year) => {
					const item = historyPassRateData.find((h: any) => h.year === year)
					return item ? item.value : null
				}),
				symbol: 'circle',
				symbolSize: 8,
				lineStyle: {
					width: 3
				},
				itemStyle: {
					color: '#909399'
				}
			},
			{
				name: '历史优秀率',
				type: 'line',
				data: allYears.map((year) => {
					const item = historyExcellentRateData.find((h: any) => h.year === year)
					return item ? item.value : null
				}),
				symbol: 'circle',
				symbolSize: 8,
				lineStyle: {
					width: 3
				},
				itemStyle: {
					color: '#67C23A'
				}
			},
			{
				name: '及格率-预测',
				type: 'line',
				data: allYears.map((year) => {
					const item = predictionPassRateData.find((p: any) => p.year === year)
					return item ? item.value : null
				}),
				symbol: 'circle',
				symbolSize: 8,
				lineStyle: {
					width: 3
				},
				itemStyle: {
					color: '#409EFF'
				}
			},
			{
				name: '及格率-下限',
				type: 'line',
				data: allYears.map((year) => {
					const item = predictionPassRateData.find((p: any) => p.year === year)
					return item ? item.lowerCI : null
				}),
				lineStyle: {
					width: 2,
					type: 'dashed'
				},
				itemStyle: {
					color: '#409EFF',
					opacity: 0.5
				}
			},
			{
				name: '及格率-上限',
				type: 'line',
				data: allYears.map((year) => {
					const item = predictionPassRateData.find((p: any) => p.year === year)
					return item ? item.upperCI : null
				}),
				lineStyle: {
					width: 2,
					type: 'dashed'
				},
				itemStyle: {
					color: '#409EFF',
					opacity: 0.5
				}
			},
			{
				name: '优秀率-预测',
				type: 'line',
				data: allYears.map((year) => {
					const item = predictionExcellentRateData.find((p: any) => p.year === year)
					return item ? item.value : null
				}),
				symbol: 'circle',
				symbolSize: 8,
				lineStyle: {
					width: 3
				},
				itemStyle: {
					color: '#E6A23C'
				}
			},
			{
				name: '优秀率-下限',
				type: 'line',
				data: allYears.map((year) => {
					const item = predictionExcellentRateData.find((p: any) => p.year === year)
					return item ? item.lowerCI : null
				}),
				lineStyle: {
					width: 2,
					type: 'dashed'
				},
				itemStyle: {
					color: '#E6A23C',
					opacity: 0.5
				}
			},
			{
				name: '优秀率-上限',
				type: 'line',
				data: allYears.map((year) => {
					const item = predictionExcellentRateData.find((p: any) => p.year === year)
					return item ? item.upperCI : null
				}),
				lineStyle: {
					width: 2,
					type: 'dashed'
				},
				itemStyle: {
					color: '#E6A23C',
					opacity: 0.5
				}
			}
		]
	}

	chartInstance.setOption(option)
}
